//x,y,z,w     Useful for points, vectors, normals
//r,g,b,a     Useful for colors
//s,t,p,q     Useful for texture coordinates 

//uniform float angle;

uniform vec2 position;
uniform int primitive;
uniform vec2 center;

uniform sampler2D normalBuffer;
uniform vec2 nbSize;
const float PI = 3.1416;

void main(void) {

	vec3 normal = texture2D (normalBuffer, center.xy).xyz;
    vec4 color;
    
    if (primitive == 2) {
        color = 1.0 - gl_Color;
    } else {
        color = gl_Color;
    }
    
    normal = 2.0 * normal - 1.0;
    
    if (normal == vec3(0.0, 0.0, 0.0) || normal == vec3(1.0, 1.0, 1.0)) {
        normal = vec3(0.0, 0.0, 1.0);
    }
    
    normal = normalize(normal);    
        
    vec3 v = vec3(0.0, 0.0, 1.0);
    vec3 p = vec3(position, 0.0);
    
    float ang = acos(dot(v, normal));
    float c = cos(ang); // angle cos
    float s = sin(ang); // angle sin
    vec3 r = cross(v, normal); // cross product    
    
    mat4 rot = mat4(r.x*r.x*(1.0-c)+c, r.y*r.x*(1.0-c)+r.z*s, r.x*r.z*(1.0-c)-r.y*s, 0.0,
                   r.x*r.y*(1.0-c)-r.z*s, r.y*r.y*(1.0-c)+c, r.y*r.z*(1.0-c)+r.x*s, 0.0,
                    r.x*r.z*(1.0-c)+r.y*s, r.y*r.z*(1.0-c)-r.x*s, r.z*r.z*(1.0-c)+c, 0.0,
                    0.0, 0.0, 0.0, 1.0);
                         
    mat4 tr1 = mat4(1.0, 0.0, 0.0, 0.0,
                    0.0, 1.0, 0.0, 0.0,
                    0.0, 0.0, 1.0, 0.0,
                    p.x, p.y, 0.0, 1.0);

    mat4 tr2 = mat4(1.0, 0.0, 0.0, 0.0,
                    0.0, 1.0, 0.0, 0.0,
                    0.0, 0.0, 1.0, 0.0,
                   -p.x,-p.y, 0.0, 1.0);
                         
    mat4 pj = gl_ProjectionMatrix * gl_ModelViewMatrix * (tr1 * rot * tr2);
        
    gl_TexCoord[0] = gl_MultiTexCoord0;
    gl_FrontColor = color;
    gl_Position = pj * vec4(gl_Vertex.xyz, 1.0);
}
